<template>
  <div id="container" class="map">
    <dv-loading style="position: absolute;z-index: 9999;color:white;" v-show="showLoading">Loading...</dv-loading>
    <picture-viewer ref="imageViewer2"></picture-viewer>
  </div>
</template>

<script>
import {workPointModelQueryByWorkPointId} from "@/services/model/project-info";
import PictureViewer from "@/components/picture-viewer/index-name";
import AMap from 'AMap'
import {mutations} from "../../../monitor/work-point.store";
import constUrl from '@/services/env'
import Vue from "vue";
import Format from '@/utils/format'
//图标渲染
const CURRENT_ICON_MAP = {
  [1]: (type) => {
    if (type === 1) {
      return require('../imgs/shenbuzaixian.png')
    } else {
      return require('../imgs/shenbu.png')
    }
  },
  [2]: (type) => {
    if (type === 1) {
      return require('./../imgs/dibiaozaixian.png')
    } else {
      return require('../imgs/dibiao.png')
    }
  },
  [3]: (type) => {
    if (type === 1) {
      return require('../imgs/laxianzaixian.png')
    } else {
      return require('../imgs/laxian.png')
    }
  },
  [4]: (type) => {
    if (type === 1) {
      return require('../imgs/jiangyuzaixian.png')
    } else {
      return require('../imgs/jiangyu.png')
    }
  },
  [5]: (type) => {
    if (type === 1) {
      return require('../imgs/dixiashuiweizaixian.png')
    } else {
      return require('../imgs/dixiashuiwei.png')
    }
  },
  [6]: (type) => {
    if (type === 1) {
      return require('../imgs/maosuozaixian.png')
    } else {
      return require('../imgs/maosuo.png')
    }
  },
  [7]: (type) => {
    if (type === 1) {
      return require('../imgs/jinglizaixian.png')
    } else {
      return require('../imgs/jingli.png')
    }
  },
  [8]: (type) => {
    if (type === 1) {
      return require('../imgs/qingjiaoZaiXian.png')
    } else {
      return require('../imgs/qingjiao.png')
    }
  },

  [10]: (type) => {
    if (type === 1) {
      return require('../imgs/wensiduzaixian.png')
    } else {
      return require('../imgs/wensidu.png')
    }
  },
  [11]: (type) => {
    if (type === 1) {
      return require('../imgs/fengshuzaixian.png')
    } else {
      return require('../imgs/fengshu.png')
    }
  },
  [12]: (type) => {
    if (type === 1) {
      return require('../imgs/yinglizaixian.png')
    } else {
      return require('../imgs/yingli.png')
    }
  },
  [13]: (type) => {
    if (type === 1) {
      return require('../imgs/zhendongzaixian.png')
    } else {
      return require('../imgs/zhendong.png')
    }
  },
}
// 渲染模板
const HTML_CONT =
  (img) => {
    return `<div class="board_map-market">
      <img src="${img}" />
    </div>`

  }
export default {
  components: {PictureViewer},
  data() {
    return {
      constUrl,
      markerClusterer: null,
      latitude: 39.742839,
      longitude: 118.18115,
      loadModelData: {},
      bmpUrl: '',
      mtlUrl: '',
      objUrl: '',
      showLoading: true,
      map: null,
      marker: null,
      // 点标记集合
      markerList: [],
    }
  },
  methods: {
    // 桥梁建模
    loadModel() {
      var that = this
      var loadModelData = that.loadModelData
      var modelName = 'building';
      var objLoader = new THREE.OBJLoader2();
      var callbackOnLoad = function (event) {
        var object3Dlayer = new AMap.Object3DLayer();
        var meshes = event.detail.loaderRootNode.children;
        for (var i = 0; i < meshes.length; i++) {
          var vecticesF3 = meshes[i].geometry.attributes.position;
          var vecticesNormal3 = meshes[i].geometry.attributes.normal;
          var vecticesUV2 = meshes[i].geometry.attributes.uv;
          var vectexCount = vecticesF3.count;
          var mesh = new AMap.Object3D.MeshAcceptLights();
          var geometry = mesh.geometry;
          //底部一圈
          var c, opacity;
          var material = meshes[i].material[0] || meshes[i].material;
          if (material.map)
            if (loadModelData.bmpUrl !== null) {
              mesh.textures.push(that.bmpUrl) //修改bmp地址
            } else {
              mesh.textures.push('')
            }
          c = material.color;
          c.setRGB(0.46274509803921, 0.51372549019, 0.5294117647058823529411)
          opacity = material.opacity
          for (var j = 0; j < vectexCount; j += 1) {
            var s = j * 3;
            geometry.vertices.push(vecticesF3.array[s], vecticesF3.array[s + 2], -vecticesF3.array[s + 1]);
            if (vecticesNormal3) {
              geometry.vertexNormals.push(vecticesNormal3.array[s], vecticesNormal3.array[s + 2], -vecticesNormal3.array[s + 1]);
            }
            if (vecticesUV2) {
              geometry.vertexUVs.push(vecticesUV2.array[j * 2], 1 - vecticesUV2.array[j * 2 + 1]);
            }
            geometry.vertexColors.push(c.r, c.g, c.b, opacity)
          }
          mesh.DEPTH_TEST = material.depthTest
          mesh.transparent = opacity < 1;
          mesh.scale(loadModelData.width, loadModelData.length, loadModelData.height)  //修改建模的长宽高
          mesh.rotateZ(loadModelData.rotate)  //修改角度
          mesh.position(new AMap.LngLat(loadModelData.longitude, loadModelData.latitude))//定位
          object3Dlayer.add(mesh)
        }
        that.map.add(object3Dlayer)
      };
      var onLoadMtl = function (materials) {
        objLoader.setModelName(modelName);
        objLoader.setMaterials(materials);
        objLoader.load(that.objUrl, callbackOnLoad, null, null, null, false);  //修改obj地址
      };
      if (loadModelData.mtlUrl !== null) {
        objLoader.loadMtl(that.mtlUrl, null, onLoadMtl);//修改mtl地址
      } else {
        objLoader.loadMtl(that.constUrl + '/oss/upload/temp/2021-08-24/1519.mtl', null, onLoadMtl);
      }
    },
    // 修改makerList
    changeMarker(typeCode) {
      this.map.clearMap()  //清除当前地图上的marker
      this.markerList = []
      let mapDataList = this.loadModelData?.monitorList
      if (typeCode) {
        mapDataList = mapDataList.filter(x => x.monitorType === typeCode)
      }
      // 信息窗口
      let _this = this
      //mouseover弹窗样式
      let content1 =
        `<el-card class="box-card">
                <ul style="padding: 10px">
                <li >
                      <el-row :gutter="10">
                             <el-col :span="12">  <span class="label_view" >监测点名称：</span><span>{{windowInfoData.name}}</span></el-col>
                             <el-col :span="12"> <span class="label_view" >监测点类型：</span><span>{{windowInfoData.monitorTypeName}}</span></el-col>
                      </el-row>
                      </li>
              <div v-if="windowInfoData.warningFlag">
                 <li>  <span class="label_view" >预警方式:</span><span class="level_view" :style="gradeColor(windowInfoData.warningFlag)">{{windowInfoData.warningFlagName}}</span></li>
              </div>
                </li>
                </ul>
        </div>
        </el-card>`
      let MyComponent1 = Vue.extend({
        template: content1,
        components: {PictureViewer},
        data() {
          return {
            constUrl: '',
          }
        },
        props: {
          windowInfoData: {
            type: Object
          }
        },
        methods: {
          // 预警颜色
          gradeColor(val) {
            switch (val) {
              case 1:
                return 'background-color:#0DC26B;color:white'
              case 0:
                return 'background-color:#0073b7;color:white'
              case 2:
                return 'background-color:#f39c12;color:white'
              case 3:
                return 'background-color:#ff851b;color:white'
              case 4:
                return 'background-color:#e43321;color:white'
              default:
                return 'background-color:#e43321;color:white'
            }
          },

        },
        created() {
          this.constUrl = _this.constUrl
        },
        mounted() {
          window.addEventListener("click", this.btnClose);
        }
      })
      //click弹窗样式
      let content =
        `<el-card class="box-card">
           <a @click="btnClose" class="btn-close amap-ui-infowindow-close amap-ui-smp-ifwn-def-tr-close">&#10006;</a>
          <div class="title ">{{windowInfoData.monitorTypeName}}详情<span style="float: right">{{windowInfoData.weather.weather}};{{windowInfoData.weather.temperature}}℃;{{windowInfoData.weather.humidity}}%</span></div>
                <ul>
                      <li>
                      <el-row :gutter="10">
                             <el-col :span="12">  <span class="label_view" >监测点名称：</span><span>{{windowInfoData.name}}</span></el-col>
                             <el-col :span="12"> <span class="label_view" >监测点类型：</span><span>{{windowInfoData.monitorTypeName}}</span></el-col>
                      </el-row>
                      </li>
                      <li>
              <div v-if="windowInfoData.warningFlag">
                   <span class="label_view" >预警方式:</span><span class="level_view" :style="gradeColor(windowInfoData.warningFlag)">{{windowInfoData.warningFlagName}}</span>
              </div>
                </li>
                 <li>
                      <el-row :gutter="10">
                             <el-col :span="12">  <span class="label_view" >创建时间：</span><span>{{windowInfoData.startTime| formatTimer}}</span></el-col>
                             <el-col :span="12"> <span class="label_view" >更新时间：</span><span>{{windowInfoData.updateTime| formatTimer}}</span></el-col>
                      </el-row>
                      </li>
                </ul>
        <picture-viewer ref="imageViewer"></picture-viewer>
        </div>
        </el-card>`
      let MyComponent = Vue.extend({
        template: content,
        components: {PictureViewer},
        data() {
          return {
            constUrl: '',
            msg: '边坡详情',
          }
        },
        props: {
          windowInfoData: {
            type: Object
          }
        },
        filters: {
          // 时间格式化
          formatTimer(timer) {
            return Format(new Date(timer), 'yyyy-MM-dd ')
          }
        },
        methods: {


          gradeColor(val) {
            switch (val) {
              case 1:
                return 'background-color:#0DC26B;color:white'
              case 0:
                return 'background-color:#0073b7;color:white'
              case 2:
                return 'background-color:#f39c12;color:white'
              case 3:
                return 'background-color:#ff851b;color:white'
              case 4:
                return 'background-color:#e43321;color:white'
              default:
                return 'background-color:#e43321;color:white'
            }
          },
          // 查看大图
          previewImg(index, urls) {
            const urlList = JSON.parse(JSON.stringify(urls));
            urlList.map((x) => {
              x.url = this.constUrl + x.url;
              return x;
            });
            // 显示照片查看器
            this.$refs.imageViewer.showViewer(urlList, index);
          },
          toControl(val, projectId) {
            _this.$router.push({
              path: `/project/${projectId}/work-point/${val.workPointId}/monitor/${val.monitorType}?activeId=${val.id}`
            })
          },
          //关闭聚合点弹窗
          btnClose() {
            _this.infoWindow.close(_this.map)
          },
        },
        created() {
          this.constUrl = _this.constUrl
        },
        mounted() {
          window.addEventListener("click", this.btnClose);
        }
      })
      if(mapDataList){
        this.markerList = mapDataList.map(x => {
          var marker = new AMap.Marker({
            content: HTML_CONT(CURRENT_ICON_MAP[x.monitorType](x.onlineStatus)),  //自定义点标记覆盖物内容    //2状态表示是在线还是离线状态
            position: [x.longitude, x.latitude],//基点位置
            height: x.height * 10,
            extData: x,
            map: this.map,
          })
          // 监听单个点移入事件
          // AMap.event.addListener(marker, 'mouseover', e => {
          //   AMap.plugin('AMap.Weather', async function () {
          //   })
          //   let extData = e.target.getExtData()
          //   // 窗体信息
          //   let component1 = new MyComponent1({ // 传参
          //     propsData: {
          //       windowInfoData: extData
          //     }
          //   }).$mount()
          //   _this.infoWindow1 = new AMap.InfoWindow({
          //     content: component1.$el, // 使用默认信息窗体框样式，显示信息内容
          //     isCustom: true,
          //     autoMove: true,
          //     anchor: 'top-center',
          //     closeWhenClickMap: true,
          //     retainWhenClose: true,
          //     offset: new AMap.Pixel(0,10),
          //   })
          //   _this.infoWindow1.open(
          //     _this.map,
          //     marker.getPosition(e.lnt, e.lat)// 窗口信息的位置
          //   )
          // })
          //监听单个点点击事件
          AMap.event.addListener(marker, 'click', e => {
            AMap.plugin('AMap.Weather', async function () {
            })
            //创建天气查询实例
            var weather = new AMap.Weather();
            //执行实时天气信息查询
            let extData = e.target.getExtData()
            let region = extData?.regionName?.split('-') || []
            region = region.length > 0 ? region : ['贵州']
            region = region[1] ? region[1] : region[0]
            weather.getLive(region, function (err, data) {
              extData.weather = data || {}
              extData.region = region
              // 窗体信息
              let component = new MyComponent({ // 传参
                propsData: {
                  windowInfoData: extData
                }
              }).$mount()
              //传数据
              mutations.setState({key: "isMarker", value: true});
              mutations.setState({key: "marker", value: extData});

              _this.infoWindow = new AMap.InfoWindow({
                content: component.$el, // 使用默认信息窗体框样式，显示信息内容
                isCustom: true,
                autoMove: true,
                closeWhenClickMap: true,
                retainWhenClose: true,
                offset: new AMap.Pixel(0, -15),
              })
              // _this.infoWindow.open(
              //   _this.map,
              //   marker.getPosition(e.lnt, e.lat)// 窗口信息的位置
              // )
            })

          })
          // 监听移除事件
          // marker.on('mouseout', e => {
          //   _this.infoWindow1.close(_this.map)
          //   // mutations.setState({key: "isMarker", value: false});
          // })
          return this.marker
        })
      }

      this.showLoading = false
    },
    // 初始化地图
    initMap() {
      this.changeData()
      this.map = new AMap.Map('container', {
        viewMode: '3D',
        expandZoomRange:true,
        rotation: 240,//左右角度
        layers: [new AMap.TileLayer.Satellite()],
        showBuildingBlock: false,
        // center: [118.18315,39.742839],
        center: [this.longitude, this.latitude],
        pitch: 65,//俯视角度
        zoom: 17, zooms: [3,22]
      });
      var roadNetLayer = new AMap.TileLayer.RoadNet();
      this.map.add(roadNetLayer);
      this.map.AmbientLight = new AMap.Lights.AmbientLight([1, 1, 1], 1);
      this.map.DirectionLight = new AMap.Lights.DirectionLight([1, 0, -0.5], [1, 1, 1], 1);
      this.changeMarker()
      this.loadModel()
    },
    //过滤数据方法
    refresh(monitorTypes) {
      this.showLoading = true
      this.changeMarker(monitorTypes)
    },
    //修改data
    changeData() {
      //修改地图坐标经纬度
      if (this.loadModelData.longitude !== null && this.loadModelData.latitude !== null) {
        this.longitude = this.loadModelData.longitude
        this.latitude = this.loadModelData.latitude
      }
      //拼接bmpUrl
      if (this.loadModelData.bmpUrl !== null) {
        this.bmpUrl = this.constUrl + this.loadModelData.bmpUrl
      } //拼接mtlUrl
      if (this.loadModelData.mtlUrl !== null) {
        this.mtlUrl = this.constUrl + this.loadModelData.mtlUrl
      }//拼接objUrl
      if (this.loadModelData.objUrl !== null) {
        this.objUrl = this.constUrl + this.loadModelData.objUrl
      }
    },
    //获取数据
    async workPointModelQueryByWorkPointId() {
      let id = this.$route.params.workPointId
      let {data} = await workPointModelQueryByWorkPointId({id})
      this.loadModelData = JSON.parse(JSON.stringify(data))
      this.showLoading = false
      this.initMap()
    }
  },
  mounted() {
    // 获取当前工点所有数据
    this.workPointModelQueryByWorkPointId()
  },
}
</script>

<style lang="less" scoped>
  .el-divider__text {
    background-color: #1b1b1b;
    padding: 3px 10px;
    border-radius: 5px;
  }

  .map {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    background-color: #0e1014;
  }

  /deep/ .box-card {

    width: 400px;
    border-radius: 0.25rem;
    border: 1px solid #266BFF;

    .btn-close {
      float: right;
      cursor: pointer;
    }

    .label_view {
      font-size: 15px;
      font-width: 600;
      margin-left: 10px;
      color: #1a253a;
    }

    .level_view {
      display: inline-block;
      padding: 0px 3px;
      border-radius: 3px;
    }

    .title {
      font-size: 20px;
      font-family: YouSheBiaoTiHei;
      white-space: nowrap;
      clear: both;
      background-color: #1a253a;
      margin-bottom: 15px;
      padding: 9px;
      color: white;
      border-radius: 5px;
    }

    .el-card__body {
      padding: 0 0.625rem;
      background: linear-gradient(to right, rgba(58, 80, 106, 0.5), #357c82);
      border-radius: 0.25rem 0.25rem 0 0;
      color: #ffffff;
      font-size: 20px;
      padding-bottom: 20px;
    }

    .el-button--success {
      color: #FFF;
      background-color: #1990FE;
      border-color: #1990FE;
    }

    .info-btn {
      margin-top: 5px;
      margin-bottom: 5px;

      .btn-item {
        margin-bottom: 7px;
        margin-right: 7px;
        background-color: #1990FE;
      }

      /deep/ .el-button + .el-button {
        margin-left: 0px;
      }
    }

    ul li {
      font-size: 13px;
      line-height: 20px;

      span:first-child {
        font-weight: bold;
      }
    }
  }
</style>
<style lang="less">
  .el-divider {
    background-color: #1b1b1b;
  }

  .board_map-market {
    .market_title {
      color: #ffffff;
      white-space: nowrap;
      text-align: center;
      margin-left: -25px;
    }

    .market_info {
      color: #2a6ef2;
      white-space: nowrap;
      font-weight: 600;
      text-align: center;
      margin-top: 6px;
      margin-left: -20px;
    }

    & > img {
      width: 36px;
      height: 36px;
    }
  }
</style>
